package com.yc.springcloud.config;

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @Author DELL
 * @Date 2024/11/19 21:38
 * @Version 1.0
 */

@Configuration
public class DataSourceProxyConfig {

	@Value("${mybatis.mapperLocations}")
	private String mapperLocations;

	/**
	 * @ConfigurationProperties告诉Spring Boot将application.properties中
	 * spring.datasource的属性绑定到DataSource的相应字段上。(获取到yml文件配置的相关信息)
	 * 然后，通过@Bean注解，Spring Boot会创建并返回一个DataSource的实例，这个实例已经包含了属性文件中定义的配置信息。
	 * @return
	 *
	 * DataSource 是 DruidDataSource 的父类类型，返回类型是函数定义的返回类型的子类或者是同级的
	 */
	@Bean
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource getDruidDataSource(){
		return new DruidDataSource();
	}


	@Bean
	public DataSourceProxy getDataSourceProxy(DataSource dataSource){
		return new DataSourceProxy(dataSource);
	}


	@Bean
	public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy)
			throws Exception {

		SqlSessionFactoryBean sqlSessionFactoryBean =
				new SqlSessionFactoryBean();

		sqlSessionFactoryBean.setDataSource(dataSourceProxy);

		sqlSessionFactoryBean.setMapperLocations
				(new PathMatchingResourcePatternResolver().getResources(mapperLocations));

		sqlSessionFactoryBean.setTransactionFactory
				(new SpringManagedTransactionFactory());

		return sqlSessionFactoryBean.getObject();
	}
}
